<template>
  <el-form-item label="规则">
    <i class="el-icon-circle-plus-outline primary-color pointer" @click="handleAddRule"></i>
    <div :key="index" v-for="(item, index) in model">
      <el-row class="form-row" :gutter="12">
        <el-col :span="5">
          <el-form-item label="是否自定义" label-width="90px">
            <el-switch v-model="item.isCustom" @change="item.rule= ''"></el-switch>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item>
            <el-select v-if="!item.isCustom" class="el-input" v-model="item.rule" placeholder="请选择规则">
            <el-option :key="index" :value="item.value" :label="item.label" v-for="(item, index) in validators"></el-option>
            </el-select>
            <el-input v-else v-model="item.rule" placeholder="请输入正则表达式"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item>
            <el-input v-model="item.message" placeholder="请输入验证失败信息"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="3" style="text-align: right">
          <i class="el-icon-delete danger-color pointer" @click="handleDeleteRule(item.id)"></i>
        </el-col>
      </el-row>
    </div>
  </el-form-item>
</template>

<script>
import PropMixin from '../prop-mixins'
import uuid from 'uuid'
import i18n from '@/components/v-form-design/utils/i18n'

export default {
  name: 'common-rules',
  mixins: [PropMixin, i18n],
  data(){
    return {
      validators:  [
          {value: 'number', label: this.i18nt('designer.hint.numberValidator')},
          {value: 'letter', label: this.i18nt('designer.hint.letterValidator')},
          {value: 'letterAndNumber', label: this.i18nt('designer.hint.letterAndNumberValidator')},
          {value: 'mobilePhone', label: this.i18nt('designer.hint.mobilePhoneValidator')},
          {value: 'email', label: this.i18nt('designer.hint.emailValidator')},
          {value: 'url', label: this.i18nt('designer.hint.urlValidator')},
          {value: 'noChinese', label: this.i18nt('designer.hint.noChineseValidator')},
          {value: 'chinese', label: this.i18nt('designer.hint.chineseValidator')},
        ],
      model: this.value
    }
  },
  methods: {
    // 添加规则
    handleAddRule(){
      this.model = _.isArray(this.model) ? this.model : []
      this.model.push({id: uuid()})
    },
    // 删除
    handleDeleteRule(id){
      const index = this.model.findIndex(item => item.id === id)
      if (index > -1){
        this.model.splice(index, 1)
      }
    }
  }
}
</script>

<style lang="scss">
.form-row {
  &:first-child .el-col {
    padding-left: 0 !important;
  }
}
.pointer{
  cursor: pointer;
  font-size: 14px;
}
.danger-color{
  color: #F56C6C;
}
</style>
